﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using IDAL;
using Models;

namespace DAL
{
    /// <summary>
    /// 公共方法基类,包含增加、删除、查询、分页查询、修改
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BaseDAL<T> where T : class,new()
    {
        /// <summary>
        /// 获取到EF上下文操作类
        /// </summary>
        public DbContext db
        {
            get
            {
                return DBFactory.CreateDbContext();
            }
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="whereLambda"></param>
        /// <returns></returns>
        public IQueryable<T> LoadData(System.Linq.Expressions.Expression<Func<T, bool>> whereLambda)
        {
            return db.Set<T>().Where(whereLambda);
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <typeparam name="c">排序类型</typeparam>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="totalCount">总页数</param>
        /// <param name="whereLambda">查询条件</param>
        /// <param name="orderbyLambda">排序条件</param>
        /// <param name="isAsc">是否倒序</param>
        /// <returns></returns>

        public IQueryable<T> Paging<c>(int pageIndex, int pageSize, out int totalCount, System.Linq.Expressions.Expression<Func<T, bool>> whereLambda, System.Linq.Expressions.Expression<Func<T, c>> orderbyLambda, bool isAsc)
        {
            var temp = db.Set<T>().Where(whereLambda);
            totalCount = temp.Count();
            if (isAsc)
            {
                temp = temp.OrderBy(orderbyLambda).Skip((pageSize - 1) * pageIndex).Take(pageSize);
            }
            else
            {
                temp = temp.OrderByDescending(orderbyLambda).Skip((pageSize - 1) * pageIndex).Take(pageSize);
            }
            return temp;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity">实体模型</param>
        public void DeleteSign(T entity)
        {
            db.Entry<T>(entity).State = EntityState.Deleted;

        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity">实体模型</param>
        public void EditSign(T entity)
        {
            db.Entry<T>(entity).State = EntityState.Modified;

        }
        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="entity">实体模型</param>
        /// <returns>返回插入成功后的实体模型</returns>
        public T AddSing(T entity)
        {
            db.Set<T>().Add(entity);
            if (db.SaveChanges() > 0)
                return entity;
            else return null;

        }

    }
}
